package logic

import (
    "context"
    "device-modbus/internal/biz/dal/mysql"
    "device-modbus/internal/biz/dao"
    "device-modbus/internal/biz/model"
    "device-modbus/internal/biz/query"
    "device-modbus/pkg/base"
    "device-modbus/pkg/util"
    "github.com/duke-git/lancet/v2/strutil"
    "github.com/jinzhu/copier"
)

type DeviceLogic struct {
    ctx context.Context
}

func NewDeviceLogic(ctx context.Context) *DeviceLogic {
    return &DeviceLogic{ctx: ctx}
}

//设备添加
func (l *DeviceLogic) Add(req *dao.DeviceAddReq) error {
    device := &model.Device{}
    if err := copier.Copy(device, req); err != nil {
        return err
    }
    return query.Q.Device.WithContext(l.ctx).Create(device)
}

//设备更新
func (l *DeviceLogic) Update(req *dao.DeviceUpdateReq) error {
    device := &model.Device{}
    if err := copier.Copy(device, req); err != nil {
        return err
    }
    return query.Q.Device.WithContext(l.ctx).Save(device)
}

//删除
func (l *DeviceLogic) Del(id string) error {
    device := &model.Device{ID: id,
    }
    _, err := query.Q.Device.WithContext(l.ctx).Delete(device)
    return err
}

//查询身ICCID
func (l *DeviceLogic) FindByIccid(iccId string) (device *model.Device, err error) {
    db := query.Q.Device
    device, err = db.WithContext(l.ctx).Where(db.Iccid.Eq(iccId)).First()
    return
}
func (l *DeviceLogic) UpdateDevice(device *model.Device) (err error) {
    db := query.Q.Device
    err = db.WithContext(l.ctx).Save(device)
    return
}

//设备查询
func (l *DeviceLogic) Search(req *dao.DeviceSearchReq) (devices []*model.Device, total *int64, err error) {
    db := mysql.DB.Model(&model.Device{}).WithContext(l.ctx)
    q := db.Order("id desc")
    if strutil.IsNotBlank(req.Name) {
        q = q.Where("name like ?", util.LikeValue(req.Name))
    }
    if strutil.IsNotBlank(req.Iccid) {
        q = q.Where("iccid = ?", req.Iccid)
    }
    if req.Online != nil {
        q = q.Where("online = ?", req.Online)
    }
    if req.Enabled != nil {
        q = q.Where("enabled = ?", req.Enabled)
    }
    err = q.Scopes(base.Paginate(&req.Page)).Find(&devices).Count(total).Error
    return
}

func (l *DeviceLogic) FindById(id string) (device *model.Device, err error) {
    db := query.Q.Device
    device, err = db.WithContext(l.ctx).Where(db.ID.Eq(id)).First()
    return
}
